<template>
  <div class="star" :class="starType">
    <span v-for="(item,index) in itemClasses" :key="index" class="star-item" :class="item"></span>
  </div>
</template>

<script>
//定义常量，之后修改更方便
const LENGTH = 5;
const CLS_ON = "on";
const CLS_HALF = "half";
const CLS_OFF = "off";

export default {
  name: "star",
  props: {
    size: {
      type: Number
    },
    score: {
      type: Number
    }
  },
  computed: {
    starType() {
      return "star-" + this.size;
      //对不同的size设定样式
    },
    itemClasses() {
      let result = []; //定义一个数组
      let score = Math.floor(this.score * 2) / 2; //对分数进行向下取0.5倍数
      let hasDecimal = score % 1 !== 0; //检查是否有小数位
      let integer = Math.floor(score); //换算整数
      for (let i = 0; i < integer; i++) {
        result.push(CLS_ON); //循环添加整颗星
      }
      if (hasDecimal) {
        result.push(CLS_HALF); //半颗星的情况只会出现1次
      }
      while (result.length < LENGTH) {
        result.push(CLS_OFF); //补齐没有的星
      }
      return result;
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '../../../common/stylus/mixins.styl'
.star
  font-size: 0
  .star-item
    display: inline-block
    background-repeat: no-repeat
  &.star-48
    .star-item
      width: 20px
      height: 20px
      margin-right: 22px
      background-size: 20px 20px
      &.last-child
        margin-right: 0
      &.on
        bgimage('./img/star48_on')
      &.half
        bgimage('./img/star48_half')
      &.off
        bgimage('./img/star48_off')
  &.star-36
    .star-item
      width: 15px
      height: 15px
      margin-right: 16px
      background-size: 15px 15px
      &.last-child
        margin-right: 0
      &.on
        bgimage('./img/star36_on')
      &.half
        bgimage('./img/star36_half')
      &.off
        bgimage('./img/star36_off')
  &.star-24
    .star-item
      width: 10px
      height: 10px
      margin-right: 3px
      background-size: 10px 10px
      &.last-child
        margin-right: 0
      &.on
        bgimage('./img/star24_on')
      &.half
        bgimage('./img/star24_half')
      &.off
        bgimage('./img/star24_off')
</style>